// 获取元素
const list = document.querySelector('.list')
const total = document.querySelector('.total');
// 渲染函数
const getStudentList = async () => {
  // 发起请求拿数据
  const { data: res } = await axios({ url: '/students' })
  // console.log(res);
  // 渲染到页面
  const htmlStr = res
    .map((item) => {
      return `
    <tr>
                        <td>${item.name}</td>
                        <td>${item.age}</td>
                        <td>${item.gender ? '男' : '女'}</td>
                        <td>第${item.group}组</td>
                        <td>${item.hope_salary}</td>
                        <td>${item.salary}</td>
                        <td>${item.province + item.city + item.area}</td>
                        <td>
                          <a href="javascript:;" class="text-success mr-3"
                            ><i class="bi bi-pen" data-id="${item.id}"></i
                          ></a>
                          <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${item.id}"></i></a>
                        </td>
                      </tr>`
    })
    .join('')
  list.innerHTML = htmlStr
  total.innerHTML = res.length
}
getStudentList()

// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')

// 获取省市区
const initCity = async () => {
  //发起请求获取省份
  const {data:res}  = await axios({ url: '/api/province' })
  // console.log(res);
  //渲染下拉框
  const provinceData = res
    .map((item) => {
      return `<option value="${item}">--${item}--</option>`
    })
    .join('')
  ps.innerHTML = `<option value="">--省份--</option>${provinceData}`

  // 省份框改变事件
  ps.addEventListener('change', async function () {
    // 根据省份获取市区
    const { data: res } = await axios({
      url: '/api/city',
      params: { pname: ps.value },
    })
    // console.log(cityList);
    //渲染城市下拉框
    const cityDaya = res
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = `<option value="">--城市--</option>${cityDaya}`
  })

  cs.addEventListener('change', async function () {
    // 根据城市获取地区
    const { data: res } = await axios({
      url: '/api/area',
      params: { pname: ps.value, cname: cs.value },
    })
    // console.log(cityList);
    //渲染城市下拉框
    const areaDaya = res
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = `<option value="">--城市--</option>${areaDaya}`
  })
}
initCity()

// 获取表单元素
const form = document.querySelector('#form')

// 点击加号打开模态框
const openModal = document.querySelector('#openModal')
openModal.addEventListener('click', function () {
  // 清空表单
  form.reset()
  modalBox.dataset.id = 'add'
  // 打开模态框
  modal.show()
})
// 添加点击事件
const submit = document.querySelector('#submit')
submit.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  data.age = +data.age
      data.gender = +data.gender
      data.hope_salary = +data.hope_salary
      data.salary = +data.salary
      data.group = +data.group
      if (data.group < 1 || data.group > 8) return alert('请输入正确的组号')
   
     modalBox.querySelector('#cb01').checked?data.gender=1:data.gender=0
  if (modalBox.dataset.id === 'add') {
    try {
      // 发起请求添加数据
      
      const res = await axios({ url: '/students', method: 'post', data })
      // console.log(res)
      // 弹出添加成功
      alert(res.message)
      // 添加成功后关闭模态框
      modal.hide()
      // xuanran 
      getStudentList()
    } catch (error) {
      alert(error)
    }
  } else {

    const res = await axios({ url: '/students/' + modalBox.dataset.id, method: 'PUT' ,data})
    alert(res.message)
      // 添加成功后关闭模态框
      modal.hide()
      // xuanran 
      getStudentList()
  }

  
})

//绑定事件委托
list.addEventListener('click',async function (e) {
  const id = e.target.dataset.id
  const nodeList = e.target.classList
  // console.log(nodeList);
  if (nodeList.contains('bi-pen')) {
    // 发起学生详情
   const res =await axios({url:'/students/'+id})
    // console.log(res);
    // 获取全部属性name
    const list = modalBox.querySelectorAll('[name]')
    // console.log(list);
   
    list.forEach(item => {
      if(item.name=== 'gender') res.data[item.name]
      ? (modalBox.querySelector('#cb01').checked = true)
      : (modalBox.querySelector('#cb02').checked = true)
      item.value = res.data[item.name]
    })
    // 获取城市
    const { data } = await axios({
      url: '/api/city',
      params: { pname: res.data.province },
    })
    // console.log(cityList);
    //渲染城市下拉框
    const cityDaya = data
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = cityDaya

    // 获取地区
    const { data:area } = await axios({
      url: '/api/area',
      params: { pname: res.data.province,cname:res.data.city },
    })
    // console.log(cityList);
    //渲染城市下拉框
    const areaDaya = area
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = areaDaya
      
    // 编辑
    modalBox.querySelector('.modal-title').innerHTML = '修改学员'
    modalBox.dataset.id = id
    modal.show()
  }
  if (nodeList.contains('bi-trash')) {
    // to do
    const id = e.target.dataset.id
    // console.log(id);
    const res = await axios({ url: '/students/' + id, method: 'DELETE', id })
    getStudentList()
    alert('删除成功')
  }
})